package ltd.newbee.mall.advice;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import ltd.newbee.mall.common.NewBeeMallException;
import ltd.newbee.mall.config.RsaKey;
import ltd.newbee.mall.config.annotation.Decrypt;
import ltd.newbee.mall.util.CryptoUtils;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.Objects;

@Slf4j
@ControllerAdvice
@Order(1)
public class EncryptRequestBodyAdvice extends RequestBodyAdviceAdapter {

    @Resource
    private RsaKey rsaKey;

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return Objects.requireNonNull(methodParameter.getMethod()).isAnnotationPresent(Decrypt.class);
    }

    @SneakyThrows
    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        String httpBody;
        if (supports(parameter, targetType, converterType)) {
            // 需要解密
            httpBody = decryptBody(inputMessage);
            if (StrUtil.isEmpty(httpBody)) {
                throw new HttpMessageNotReadableException("request body decrypt error", inputMessage);
            }
        } else {
            httpBody = StreamUtils.copyToString(inputMessage.getBody(), Charset.defaultCharset());
        }
        return new SecretHttpMessage(new ByteArrayInputStream(httpBody.getBytes()), inputMessage.getHeaders());
    }

    private String decryptBody(HttpInputMessage inputMessage) throws Exception {
        InputStream encryptStream = inputMessage.getBody();
        String encryptBody = StreamUtils.copyToString(encryptStream, Charset.defaultCharset());
        ReqSecretData reqSecret = JSONObject.parseObject(encryptBody, ReqSecretData.class);
        log.info("请求加密数据 decryptBody = {}", reqSecret);
        String signature = DigestUtil.md5Hex(reqSecret.getTimestamp() + reqSecret.getSecurityKey() + reqSecret.getSecretData());
        if (!signature.equals(reqSecret.getSignature())) {
            NewBeeMallException.fail("签名无效");
        }
        // 解密AES 密钥
        String aesKey = Base64.encode(CryptoUtils.decryptByRSA(rsaKey.getPrivateKey(), reqSecret.getSecurityKey()));
        // 解密数据
        return CryptoUtils.decryptSymmetrically(aesKey, aesKey, reqSecret.getSecretData(), CryptoUtils.Algorithm.AES_CBC_PKCS5);
    }
}
